<template>
  <div class="room-list">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>房间列表</span>
          <el-button v-if="isLoggedIn" type="primary" size="small" @click="showAddRoomDialog">新增房间</el-button>
        </div>
      </template>

      <el-table :data="rooms" style="width: 100%">
        <el-table-column prop="roomNumber" label="房间号" align="center" />
        <el-table-column prop="roomType" label="房间类型" align="center" />
        <el-table-column prop="price" label="价格" align="center">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" :disabled="scope.row.status !== '空闲'"
              @click="handleBooking(scope.row)">
              预约
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 预约对话框 -->
    <el-dialog v-model="dialogVisible" title="填写客户信息" width="30%">
      <el-form :model="customerForm" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="customerForm.name"></el-input>
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="customerForm.idCard"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="customerForm.phone"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBooking">确定预订</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增房间对话框 -->
    <el-dialog v-model="addRoomDialogVisible" title="新增房间" width="30%">
      <el-form :model="newRoomForm" label-width="80px">
        <el-form-item label="房间号">
          <el-input v-model="newRoomForm.roomNumber"></el-input>
        </el-form-item>
        <el-form-item label="房间类型">
          <el-select v-model="newRoomForm.roomType" placeholder="请选择房间类型">
            <el-option label="标准间" value="标准间" />
            <el-option label="大床房" value="大床房" />
            <el-option label="套房" value="套房" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model.number="newRoomForm.price"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addRoomDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitNewRoom">提交</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, onUnmounted, watch } from 'vue'
import { ElMessage, ElDialog, ElForm, ElFormItem, ElInput } from 'element-plus'
import { onBeforeRouteUpdate } from 'vue-router';

interface Room {
  roomID: number
  roomNumber: string
  roomType: string
  price: number
  status: string
}

interface Customer {
  customerID?: number // 后端生成，这里可选
  name: string
  idCard: string
  phone: string
}

const rooms = ref<Room[]>([])
const dialogVisible = ref(false) // 控制对话框显示
const customerForm = reactive<Customer>({
  name: '',
  idCard: '',
  phone: '',
}) // 客户表单数据
const selectedRoom = ref<Room | null>(null) // 存储当前选择的房间

// 添加登录状态变量和检查方法
const isLoggedIn = ref(false);

const checkLoginStatus = () => {
  const adminFlag = localStorage.getItem('admin');
  isLoggedIn.value = !!adminFlag;
};

// 通过 watch 监听 localStorage 的 admin 变化（定时器方案）
const adminWatcher = setInterval(() => {
  checkLoginStatus();
}, 500);

onUnmounted(() => {
  window.removeEventListener('storage', checkLoginStatus);
  clearInterval(adminWatcher);
});

// 获取房间列表数据
const fetchRooms = async () => {
  try {
    const response = await fetch('http://127.0.0.1:8080/api/rooms/all')
    const data = await response.json()
    rooms.value = data
  } catch (error) {
    ElMessage.error('获取房间列表失败')
    console.error('Error fetching rooms:', error)
  }
}

// 根据状态返回不同的标签类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    '空闲': 'success',
    '占用': 'danger',
    '预订': 'warning',
    '清洁中': 'info'
  }
  return statusMap[status] || 'info'
}

// 处理预约按钮点击
const handleBooking = (room: Room) => {
  selectedRoom.value = room
  // 重置表单
  customerForm.name = '';
  customerForm.idCard = '';
  customerForm.phone = '';
  dialogVisible.value = true
}

// 提交预订信息
const submitBooking = async () => {
  if (!selectedRoom.value) {
    ElMessage.error('未选择房间');
    return;
  }
  const roomId = selectedRoom.value.roomID;

  try {
    const response = await fetch(`http://127.0.0.1:8080/api/booking/reserve/${roomId}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(customerForm),
    });

    const result = await response.text(); // 假设后端返回的是纯文本的成功/失败消息

    if (response.ok) {
      ElMessage.success(result);
      dialogVisible.value = false; // 关闭对话框
      fetchRooms(); // 刷新房间列表
    } else {
      ElMessage.error(`预订失败: ${result}`);
    }

  } catch (error) {
    ElMessage.error('提交预订失败');
    console.error('Error submitting booking:', error);
  }
}

onMounted(() => {
  fetchRooms();
  checkLoginStatus(); // 在组件加载时检查登录状态
  // 监听 localStorage 变化，自动刷新登录状态
  window.addEventListener('storage', checkLoginStatus);
});

// 离开页面时移除监听，防止内存泄漏
onUnmounted(() => {
  window.removeEventListener('storage', checkLoginStatus);
});

// 监听路由切换，确保每次进入页面都刷新登录状态
onBeforeRouteUpdate(() => {
  checkLoginStatus();
});

// 新增房间相关的状态和方法
const addRoomDialogVisible = ref(false);
const newRoomForm = reactive({
  roomNumber: '',
  roomType: '',
  price: null,
});

const showAddRoomDialog = () => {
  addRoomDialogVisible.value = true;
  // 清空表单
  newRoomForm.roomNumber = '';
  newRoomForm.roomType = '';
  newRoomForm.price = null;
};

const submitNewRoom = async () => {
  // 校验表单
  if (!newRoomForm.roomNumber || !newRoomForm.roomType || newRoomForm.price == null) {
    ElMessage.error('请填写完整的房间信息');
    return;
  }
  try {
    const response = await fetch('http://127.0.0.1:8080/api/rooms/add', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(newRoomForm),
    });
    const result = await response.text();
    if (response.ok && result.includes('成功')) {
      ElMessage.success(result);
      addRoomDialogVisible.value = false;
      fetchRooms(); // 新增成功后刷新列表
    } else {
      ElMessage.error(result || '新增房间失败');
    }
  } catch (error) {
    ElMessage.error('新增房间请求失败');
    console.error('Error adding room:', error);
  }
};

</script>

<style scoped>
.room-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  width: 100%;
  margin-bottom: 20px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>